package router

import (
	"context"
	"log"
	"time"

	"go.etcd.io/etcd/clientv3"
	"go.etcd.io/etcd/mvcc/mvccpb"
)

var (
	etcdConfig clientv3.Config
	EtcdClient *clientv3.Client
	//Etcdkv     clientv3.KV
)

// 这个文件用来操作etcd
func init() {
	// 配置etcd 默认在本地
	etcdConfig = clientv3.Config{
		Endpoints:   []string{"127.0.0.1:2379"},
		DialTimeout: 5 * time.Second,
	}
	// 建立一个客户端
	if EtcdClient, err = clientv3.New(etcdConfig); err != nil {
		log.Fatalln(err)
	}
}
func EtcdPut(key string, value string) {
	ctx, cancle := context.WithTimeout(context.Background(), 3*time.Second)
	_, err := EtcdClient.Put(ctx, key, value)
	if err != nil {
		cancle()
	}
}
func EtcdGetSingle(key string) []byte {
	ctx, cancle := context.WithTimeout(context.Background(), 3*time.Second)
	if res, err := EtcdClient.Get(ctx, key); err != nil {
		cancle()
		return nil
	} else {
		// 获取成功
		if len(res.Kvs) == 0 {
			return nil
		}
		return res.Kvs[0].Value
	}
}
func EtcdGetMulti(key string) []*mvccpb.KeyValue {
	ctx, cancle := context.WithTimeout(context.Background(), 3*time.Second)
	if res, err := EtcdClient.Get(ctx, key); err != nil {
		cancle()
		return nil
	} else {
		// 获取成功
		if len(res.Kvs) == 0 {
			return nil
		}
		return res.Kvs
	}
}
